	package com.yashi.service.impl;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yashi.dao.TbUserChatMapper;
import com.yashi.dao.TbUserMapper;
import com.yashi.entity.TbUser;
import com.yashi.entity.TbUserChat;
import com.yashi.service.UserChatService;
import com.yashi.utils.YSUtils;
@Service
public class UserChatServiceImpl implements UserChatService{
	@Autowired
	private TbUserChatMapper userChatDao;
	@Autowired
	private TbUserMapper userDao;
	@Override
	public PageInfo<TbUserChat> selectUserChat(TbUserChat userChat,Integer startPage,HttpSession session) {
		TbUser user = (TbUser) session.getAttribute("user");
		userChat.setSendId(user.getId());
		userChat.setSendName(user.getUsername());
		if(startPage==null || startPage ==0) {
			PageHelper.startPage(1,10);
		}else{
			PageHelper.startPage(startPage,10);	
		}
		List<TbUserChat> userChatLsit = userChatDao.selectUserChat(userChat);
		//将所有消息置为已读
			Integer updateUserChat = updateUserChat(userChat, session);
			System.out.println("重置消息状态数"+updateUserChat);
		PageInfo<TbUserChat> pageInfo  =new PageInfo<TbUserChat>(userChatLsit);
		return pageInfo;
	}
	@Override
	public PageInfo<TbUserChat> selectUserFiles(TbUserChat userChat, Integer startPage, HttpSession session) {
		TbUser user = (TbUser) session.getAttribute("user");
		userChat.setSendId(user.getId());
		userChat.setSendName(user.getUsername());
		if(startPage==null || startPage ==0) {
			PageHelper.startPage(1,10);
		}else{
			PageHelper.startPage(startPage,10);	
		}
		List<TbUserChat> userChatLsit = userChatDao.selectUserFiles(userChat);
		PageInfo<TbUserChat> pageInfo  =new PageInfo<TbUserChat>(userChatLsit);
		return pageInfo;
	}
	@Override
	public PageInfo<TbUserChat> selectGroupChat(TbUserChat userChat,Integer startPage) {
		if(startPage==null || startPage ==0) {
			PageHelper.startPage(1,10);
		}else{
			PageHelper.startPage(startPage,10);	
		}
		List<TbUserChat> userChatLsit = userChatDao.selectGroupChat(userChat);
		PageInfo<TbUserChat> pageInfo  =new PageInfo<TbUserChat>(userChatLsit);
		return pageInfo;
	}
	@Override
	public PageInfo<TbUserChat>  selectFiles(Integer startPage,String receiveId) {
		if(startPage==null || startPage ==0) {
			PageHelper.startPage(1,10);
		}else{
			PageHelper.startPage(startPage,10);	
		}
		List<TbUserChat> filesList = userChatDao.selectFiles(receiveId);
		PageInfo<TbUserChat> pageInfo  =new PageInfo<TbUserChat>(filesList);
		return pageInfo;
	}

	@Override
	public TbUserChat saveUserChat(TbUserChat userChat,HttpSession session) {
		TbUser user = (TbUser) session.getAttribute("user");
		userChat.setId(YSUtils.getUUID());
		userChat.setSendId(user.getId());
		userChat.setSendName(user.getUsername());
		userChat.setDelFlag("0");
		userChat.setIsread("0");
		userChat.setCreateDate(YSUtils.getCurrentTime());
		 userChatDao.insertSelective(userChat);
		return userChat;
	}
	@Override
	public Integer updateUserChat(TbUserChat userChat,HttpSession session) {
		List<TbUserChat> userChatList = userChatDao.selectIsReadUserChat(userChat);
		int a=0;
		for (TbUserChat tbUserChat : userChatList) {
			if(!userChat.getSendId().equals(tbUserChat.getSendId())) {
				tbUserChat.setIsread("1");
				userChatDao.updateByPrimaryKeySelective(tbUserChat);
				a++;
			}
			if(userChat.getSendId().equals(tbUserChat.getSendId()) &&userChat.getSendId().equals(tbUserChat.getReceiveId())) {
				tbUserChat.setIsread("1");
				userChatDao.updateByPrimaryKeySelective(tbUserChat);
				a++;
			}
		}
		return a;
	}
	//以下是多余的
/*
	@Override
	public Integer saveGroupChat(TbUserChat userChat,HttpSession session) {
		TbUser user = (TbUser) session.getAttribute("user");
		userChat.setId(YSUtils.getUUID());
		userChat.setSendId(user.getId());
		userChat.setSendName(user.getUsername());
		userChat.setType("1");
		userChat.setDelFlag("0");
		userChat.setCreateDate(YSUtils.getCurrentTime());
		Integer count = userChatDao.insertSelective(userChat);
		return count;
	}*/

	@Override
	public List<TbUserChat> multifileUpload(HttpServletRequest request, TbUserChat userChat) {
		
		 List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
	        
	        if(files.isEmpty()){
	        	System.out.println("文件为空");
	            return null;
	        }
	        
	        String path1 = request.getContextPath();
	        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path1+"/fileupload/";
	        String filePath = request.getSession().getServletContext().getRealPath("fileupload/");
	        
	        String path = filePath ;
	        List<TbUserChat> userChatList =new  ArrayList<TbUserChat>();
	        for(MultipartFile file:files){
	            String fileName = file.getOriginalFilename();
	            //放入id
	            userChat.setId(YSUtils.getUUID());
	            //放入文件名用于前台展示
	            userChat.setFileName(fileName);
	            //获取文件后缀名
	            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
	            suffix =suffix.toLowerCase();
//	            if("jpg".equals(suffix) || "png".equals(suffix) || "gif".equals(suffix)) {
//	            	userChat.setFiletype("0");
//	            }else {
//	            	userChat.setFiletype("1");
//	            }
	            //放入前台展示url
	            userChat.setFileUrl(basePath+YSUtils.getFileCurrentTime()+fileName);
	            //将前台展示URL放入聊天记录中，以便查询
	            userChat.setContent(basePath+YSUtils.getFileCurrentTime()+fileName);
	    		//设置为未删除
	    		userChat.setDelFlag("0");
	    		//设置创建时间
	    		userChat.setCreateDate(YSUtils.getCurrentTime());
	            int size = (int) file.getSize();
	            System.out.println(fileName + "-->" + size);
	            //为防止文件被覆盖设置服务器文件名为时间加文件名
	            fileName = YSUtils.getFileCurrentTime()+fileName;
	            userChat.setIsread("0");
	            if(file.isEmpty()){
	                return null;
	            }else{        
	                File dest = new File(path + "/" + fileName);
	                if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
	                    dest.getParentFile().mkdir();
	                }
	                try {
	                    file.transferTo(dest);
	                    if(userChat.getFiletype().equals("3")) {//如果是视频，进行截图
	                    	String jpgUrl =path + "/" +fileName.substring(0,fileName.lastIndexOf("."))+".jpg";//设置截图存放路径
	                    	String vdioUrl =path + "/" + fileName;//获取视频路径
	                    	fetchFrame(vdioUrl,jpgUrl);//调用视频截图方法
	                    	userChat.setContent(basePath+fileName.substring(0,fileName.lastIndexOf("."))+".jpg");//修改消息内容
	                    }
	                    //保存文件上传记录
	                    userChatDao.insertSelective(userChat);
	                    userChatList.add(userChat);
	                }catch (Exception e) {
	                    e.printStackTrace();
	                    return null;
	                } 
	            }
	        }
	        return userChatList;
	}
	@Override
	public List<TbUser> findUserChatList(HttpSession session) {
		TbUser user = (TbUser) session.getAttribute("user");
		String id=user.getId();
		List<TbUser> userList = userDao.findUserChatList(id);
		List<TbUser> userList2 = new ArrayList<>();
		for (TbUser tbUser : userList) {
			String isReadCount = userDao.findUserChatList2(user.getId(),tbUser.getId());
			tbUser.setReadCount(isReadCount);
			userList2.add(tbUser);
		}
		return userList2;
	}
	@Override
	public List<TbUserChat> selectLastUserChat(TbUserChat userChat, HttpSession session) {
		TbUser user = (TbUser) session.getAttribute("user");
		userChat.setSendId(user.getId());
		userChat.setSendName(user.getUsername());
		List<TbUserChat> laseUserChat = userChatDao.selectLastUserChat(userChat);
		return laseUserChat;
	}
	@Override
	public List<TbUserChat> selectLastGroupChat(TbUserChat userChat) {
		List<TbUserChat> lastGroupChat = userChatDao.selectLastGroupChat(userChat);
		return lastGroupChat;
	}
	
	/**
	 * 获取指定视频的帧并保存为图片至指定目录
	 * @param videofile  源视频文件路径
	 * @param framefile  截取帧的图片存放路径
	 * @throws Exception
	 */
	public static void fetchFrame(String videofile, String framefile)
	        throws Exception {
		File file =new File(videofile);
		@SuppressWarnings("resource")
		FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);
        ff.start();
        int lenght = ff.getLengthInAudioFrames();
        System.out.println(ff.getFrameRate());

        int i = 0;
        Frame frame = null;
        while (i < lenght) {
            // 过滤前5帧，避免出现全黑的图片，依自己情况而定
            frame = ff.grabImage();
//            if (i>=(int) (ff.getFrameRate()*second)&&frame.image != null) {
            System.out.print(i+",");
            if(i==50){
                int a =1;
            }
            if(frame!=null&&frame.image!=null) {
                System.out.println(i);
                writeToFile(frame, i,framefile);
            }
//                second++;
//            }
            i++;
        }
        ff.stop();
    }

    public static void writeToFile(Frame frame,int second,String imgUrl){
        File targetFile = new File(imgUrl);
        String imgSuffix = "jpg";

        Java2DFrameConverter converter =new Java2DFrameConverter();
        BufferedImage srcBi =converter.getBufferedImage(frame);
        int owidth = srcBi.getWidth();
        int oheight = srcBi.getHeight();
        // 对截取的帧进行等比例缩放
        int width = 800;
        int height = (int) (((double) width / owidth) * oheight);
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        bi.getGraphics().drawImage(srcBi.getScaledInstance(width, height, Image.SCALE_SMOOTH),0, 0, null);
        try {
            ImageIO.write(bi, imgSuffix, targetFile);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
